/**
 * Created by wenchuan on 2017/9/4.
 */
(function () {

    var self, mAddress,mSalesReport;

    function Map() {
        self = this;

        self.init();
    }

    Map.prototype.init = function () {
        app.tag_city = '_tag_city';
        var map, mAutocomplete, geolocation, placeSearch, mGeocoder;
        var _lng = app.lStorage.get(app.tag_longitude);
        var _lat = app.lStorage.get(app.tag_latitude);
        if (!_lng) {
            _lng = 120.296474;
            _lat = 30.444385;
            //mapContainer
            map = new AMap.Map('container', {
                zoom: 14,
                center: [_lng, _lat],
                resizeEnable: true
            });
            //document.getElementById('msgBox').style.display = 'block';
            geolocationFun(autocomplete);
        } else {
            //mapContainer
            map = new AMap.Map('container', {
                zoom: 14,
                center: [_lng, _lat],
                resizeEnable: true
            });
            autocomplete({addressComponent: {citycode: app.lStorage.get(app.tag_city)}});
            setTimeout(function () {
                geolocationFun();
            }, 800);
        }

        //浏览器定位
        function geolocationFun(cb) {
            map.plugin('AMap.Geolocation', function () {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: false,//是否使用高精度定位，默认:true
                    maximumAge: 600,//缓存10分钟
                    showCircle: false,
                    noIpLocate: 0,//1: 手机设备禁止使用IP定位
                    buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: false     //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    //buttonPosition: 'RB'
                });
                geolocation.getCurrentPosition();
                // map.addControl(geolocation);
                AMap.event.addListener(geolocation, 'complete', function (e) {
                    //TODO
                    _lng = e.position.lng;
                    _lat = e.position.lat;
                    if (cb) {
                        placeSearchFun();
                        cb(e);
                    }
                    //document.getElementById('msgBox').style.display = 'none';
                    //限制城市
                    //if (mAutocomplete) {
                    //mAutocomplete.setCity(e.addressComponent.citycode);
                    //}
                    app.lStorage.set(app.tag_latitude, _lat);
                    app.lStorage.set(app.tag_longitude, _lng);
                    app.lStorage.set(app.tag_city, e.addressComponent.citycode);
                });
                AMap.event.addListener(geolocation, 'error', function (e) {
                    //alert('地图定位出错，请重新进入页面');
                    //geolocation.getCurrentPosition();
                    // mGeocoder.getAddress([fromObj.location.lng, fromObj.location.lat], function (status, result) {
                    //     if (status === 'complete' && result.info === 'OK') {
                    //         var dobj = result.regeocode.addressComponent;
                    //         mAddAddressData.PROVINCE_NAME = fromObj.pname || dobj.province;
                    //         mAddAddressData.CITY_NAME = fromObj.cityname;
                    //     }
                    // });
                });
            });
        }

        //加载Autocomplete插件
        function autocomplete(e) {
            AMap.service(["AMap.Autocomplete"], function () {
                try {
                    mAutocomplete = new AMap.Autocomplete({
                        //    city: e.addressComponent.citycode,
                        input: "tipinput",
                        datatype: 'poi'
                    });
                    autoSelect();
                } catch (_e) {
                    console.log(_e);
                }
            });
        }

        //加载Geocoder插件
        function geocoderFun() {
            AMap.service(["AMap.Geocoder"], function () {
                try {
                    mGeocoder = new AMap.Geocoder({
                        batch: false,
                        radius: 500
                    });
                } catch (_e) {
                    console.log(_e);
                }
            });
        }

        //加载PlaceSearch插件
        function placeSearchFun() {//, "AMap.Autocomplete"
            AMap.service(["AMap.PlaceSearch"], function () {
                try {
                    //构造地点查询类
                    placeSearch = new AMap.PlaceSearch({
                        pageSize: 40,
                        pageIndex: 1,
                        map: map,
                        panel: "poiList",
                        showCover: false
                    });
                    //placeSearch.setType('商务住宅|公司企业');
                    placeSearch.searchNearBy("小区|苑|坝|园|处|院|号|弄|巷|村|店|坊|业|住宅|门|区|校|大学", [_lng, _lat], 4000, function (status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            if (result.pois && results.pois.length > 0) {
                                $('#panel').toggleClass('empty');
                            }
                            //显示结果列表
                            $('#panel').removeClass('hidden');
                            //隐藏loading状态
                            $(document.body).removeClass('searching');
                        }
                    });

                    checkPoiList();

                    //监听搜索列表的渲染完成事件
                    AMap.event.addListener(placeSearch, 'renderComplete', function () {
                        checkPoiList();
                    });

                    var selectChanged = false;

                    //监听marker/列表的选中事件
                    AMap.event.addListener(placeSearch, 'selectChanged', function (results) {
                        if(selectChanged){
                            return;
                        }
                        selectChanged = true;
                        //获取当前选中的结果数据
                        var fromObj = results.selected.data;
                        //mGeocoder.setCity(fromObj.adcode);
                        //mGeocoder.getAddress([fromObj.location.lng, fromObj.location.lat],function (status,result) {

                        var requestArgs = app.pageParameters['map_page'];
                        requestArgs.cb&&requestArgs.cb(fromObj);

                        //mSalesReport.data.signatureAds = fromObj.pname + fromObj.cityname + fromObj.adname + fromObj.address;

                        parent.mui.back();
                    });

                } catch (_e) {
                    console.log(_e);
                }
            });
        }

        //搜索框支持自动完成提示
        function autoSelect() {
            //监听搜索框的提示选中事件
            AMap.event.addListener(mAutocomplete, "select", function (eSelect) {
                //设置搜索的城市
                placeSearch.setCity(eSelect.poi.adcode);
                var searchStr = eSelect.poi.name;
                //for (var i = eSelect.poi.name.length -1; i >= 2; i--) {
                //searchStr += ('|' + eSelect.poi.name.substr(0, i));
                //}
                //app.log(searchStr)
                placeSearch.searchNearBy(searchStr, [eSelect.poi.location.lng, eSelect.poi.location.lat], 45000, function (status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        if (result.pois && results.pois.length > 0) {
                            $('#panel').toggleClass('empty');
                        }
                        //显示结果列表
                        $('#panel').removeClass('hidden');
                    }
                    //隐藏loading状态
                    $(document.body).removeClass('searching');
                });

                //开始搜索对应的poi名称
                // placeSearch.search(eSelect.poi.name, function (status, results) {
                //     if (results.pois && results.pois.length > 0) {
                //         $('#panel').toggleClass('empty');
                //     }
                //     //显示结果列表
                //     $('#panel').removeClass('hidden');
                //     //隐藏loading状态
                //     $(document.body).removeClass('searching');
                // });

                //显示loading状态
                $(document.body).addClass('searching');
            });
        }

        //检查结果列表是否为空， 为空时显示必要的提示，即#emptyTip
        function checkPoiList() {
            $('#panel').toggleClass('empty', !($.trim($('#poiList').html())));
        }

        setTimeout(function () {
            placeSearchFun();
            geocoderFun();
            map.plugin(["AMap.ToolBar"], function () {
                map.addControl(new AMap.ToolBar());
            });
            $('#showHideBtn').click(function () {
                $('#panel').toggleClass('hidden');
            });
            $('#clearSearchBtn').click(function () {

                //清除搜索框内容
                $('#tipinput').val('');
                //清除结果列表
                //placeSearch.clear();
                //$('#panel').addClass('hidden');
                checkPoiList();
            });
        }, 150);

    };

    var mMap = new Map();

    if (typeof exports == "object") {
        module.exports = mMap;
    } else if (typeof define == "function" && define.amd) {
        define([], function () {
            return mMap;
        });
    } else {
        window.init = function () {
            mMap.init();
        };
    }
})();


